﻿using System;
using System.Web.Mvc;
using Actya.Core;
using Actya.Core.Content;
using Actya.Core.Infrastructure;
using Actya.Core.Widgets;
using Actya.Web.Infrastructure.AntiForgery;
using Actya.Web.Mvc.Helpers;
using Actya.Web.ViewModels.Admin;

namespace Actya.Web.Controllers.CmsAdmin
{
	[Authorize(Roles = RoleNames.CmsAdministrators)]
	public class WidgetsController : Controller
    {
		private readonly ICmsContext _cmsContext;
    	private readonly IWidgetService _widgetService;

    	public WidgetsController(ICmsContext cmsContext, IWidgetService widgetService)
    	{
    		_cmsContext = cmsContext;
    		_widgetService = widgetService;
    	}

        public ActionResult Index()
    	{
    		var widgetTypes = _cmsContext.Site.WidgetTypes;
			return View(widgetTypes);
		}

		public ActionResult Edit(string widgetId)
		{
			var widget = _widgetService.GetWidgetById(widgetId);
//			widget.Initialize(this._cmsContext);
			return PartialView("_Edit", new EditWidgetViewModel { Widget = widget });
		}

		[HttpPost]
		[ValidateInput(false)]
		[AjaxValidateAntiForgeryToken]
		public ActionResult Edit(EditWidgetViewModel viewModel)
		{
			try
			{
				var widget = viewModel.Widget;
				widget.SanitizeContent(HtmlSanitizer.sanitize);
				_widgetService.Save(widget);
				this.ShowMessage(MessageType.Success, "Widget is updated successfully.");
			}
			catch (Exception ex)
			{
				this.ShowMessage(MessageType.Error, ex.ToString());
			}
			return Json("Success");
		}
    }
}
